<template>
  <div class="news-edit-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900 ">编辑新闻</h1>
          <p class="text-gray-600  mt-1">修改新闻内容</p>
        </div>
        <div class="flex space-x-3">
          <el-button type="info" @click="handlePreview" class="w-[90px]">
            预览
          </el-button>
          <el-button type="success" @click="handleSave" :loading="saving" class="w-[90px]">
            保存
          </el-button>
          <el-button type="danger" @click="handleDelete" class="w-[90px]">
            删除
          </el-button>
          <el-button type="default" @click="handleCancel" class="w-[90px]">
            取消
          </el-button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 使用共享的新闻表单组件 -->
    <div v-else class="form-container">
      <NewsForm
        ref="newsFormRef"
        mode="edit"
        :news-id="newsId"
        :initial-data="newsData"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import NewsForm from '~/components/admin/NewsForm.vue'
import { adminNewsAPI } from '~/services/api'

// 定义页面布局
definePageMeta({
  layout: 'admin'
})

const router = useRouter()
const route = useRoute()
const newsFormRef = ref()
const loading = ref(true)
const saving = ref(false)

// 获取新闻ID
const newsId = computed(() => route.params.id)

// 新闻数据
const newsData = ref({})

// 加载新闻详情
const loadNewsDetail = async () => {
  try {
    loading.value = true
    
    // 调用后端API获取新闻详情
    const news = await adminNewsAPI.getNewsById(newsId.value)
    
    if (!news) {
      ElMessage.error('新闻不存在')
      router.push('/admin/news/list')
      return
    }
    
    // 设置新闻数据
    newsData.value = {
      id: news.id,
      title: news.title,
      summary: news.summary,
      content: news.content,
      author: news.author,
      wordCount: news.wordCount,
      viewCount: news.viewCount,
      isHot: news.isHot,
      categoryId: news.categoryId,
      categoryName: news.categoryName,
      sourceId: news.sourceId,
      sourceName: news.sourceName,
      url: news.url,
      imageUrl: news.imageUrl,
      publishTime: news.publishTime,
      status: news.status,
      createdAt: news.createdAt
    }
    
  } catch (error) {
    console.error('加载新闻详情失败:', error)
    ElMessage.error('加载新闻详情失败')
  } finally {
    loading.value = false
  }
}

// 保存新闻
const handleSave = async () => {
  try {
    saving.value = true
    
    // 验证表单
    const valid = await newsFormRef.value?.validate()
    if (!valid) return
    
    // 获取表单数据
    const formData = newsFormRef.value?.formData
    
    // 调用后端API更新新闻
    await adminNewsAPI.updateNews(newsId.value, formData)
    
    ElMessage.success('新闻修改成功')
    router.push('/admin/news/list')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

// 删除新闻
const handleDelete = async () => {
  try {
    // 调用后端API删除新闻
    await adminNewsAPI.deleteNews(newsId.value)
    
    ElMessage.success('新闻删除成功')
    router.push('/admin/news/list')
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败，请重试')
  }
}

// 预览新闻
const handlePreview = () => {
  newsFormRef.value?.handlePreview()
}

// 取消操作
const handleCancel = async () => {
  // 检查是否有未保存的修改
  // 这里可以添加更复杂的变更检测逻辑
  try {
    await ElMessageBox.confirm(
      '确定要离开吗？未保存的修改将会丢失。',
      '确认离开',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    router.push('/admin/news/list')
  } catch {
    // 用户取消离开
  }
}

// 页面初始化
onMounted(async () => {
  await loadNewsDetail()
})
</script>

<style scoped>
.news-edit-page {
  @apply min-h-screen bg-gray-50 ;
}

.page-header {
  @apply bg-white  shadow-sm border-b border-gray-200  px-6 py-4 mb-6;
}

.loading-container {
  @apply px-6 pb-6;
}

.form-container {
  @apply px-6 pb-6;
}
</style>